class Solution
{
public:
    int minOperations(int n)
    {
        string s;
        int oneBit = __builtin_popcount(n);
        while (n)
        {
            if (n & 1)
            {
                s.push_back('1');
            }
            else
            {
                s.push_back('0');
            }
            n = n >> 1;
        }

        int zeroCount = 0;
        int oneCount = 0;
        int result = 0;
        int i = 0;
        while (i < s.size() && s[i] == '0')
        {
            ++i;
        }
        while (i < s.size())
        {
            if (s[i] == '1')
            {
                ++oneCount;
            }
            else
            {
                if (i > 0 && s[i - 1] == '0')
                {
                    if (oneCount == 1)
                    {
                        result += 1;
                    }
                    else if (oneCount > 1)
                    {
                        result += min(oneCount, zeroCount + 1);
                    }
                    oneCount = 0;
                    zeroCount = 0;
                }
                else
                {
                    ++zeroCount;
                }
            }
            ++i;
        }
        if (oneCount == 1)
        {
            result += 1;
        }
        else if (oneCount > 1)
        {
            result += min(oneCount, zeroCount + 2);
        }

        return result;
    }
};